package com.example.demo.hutool.redis.stream;

import redis.clients.jedis.*;


import java.util.List;
import java.util.Map;

public class StreamServiceImpl implements IStreamServer {

    public static JedisPool jedisPool;

    static {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大连接数
        jedisPoolConfig.setMaxTotal(10);
        // 最大连接阻塞等待时间
        jedisPoolConfig.setMaxWaitMillis(-1);
        // 最大空闲连接数
        jedisPoolConfig.setMaxIdle(1);
        // 最小空闲连接数
        jedisPoolConfig.setMinIdle(1);
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);
        int to = 500000;
        jedisPool = new JedisPool(jedisPoolConfig, "172.20.54.121", 6382, to, null);
    }

    @Override
    public StreamEntryID xadd(String key, StreamEntryID streamEntryID, Map<String, String> content) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.xadd(key, streamEntryID, content);
        }
    }

    @Override
    public String xgroupCreate(String stream, String group, Boolean makeStream) {
        try (Jedis jedis = jedisPool.getResource()) {
            try {
                return jedis.xgroupCreate(stream, group, null, makeStream);
            } catch (Exception e) {
             //   jedis.xgroupDestroy(stream,group);
                return null;
            }
        }
    }

    @Override
    public List<StreamEntry> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.xrevrange(key, end, start, count);
        }
    }

    @Override
    public List<StreamEntry> xrange(String key, StreamEntryID start, StreamEntryID end, int count) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.xrange(key, start, end, count);
        }
    }

    @Override
    public List<Map.Entry<String, List<StreamEntry>>> xreadGroup(String group, String consumer, int count, Map.Entry<String, StreamEntryID>... streams) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.xreadGroup(group, consumer, count, 0, false, streams);
        }
    }

    @Override
    public List<Map.Entry<String, List<StreamEntry>>> xread(int count, Map.Entry<String, StreamEntryID>... streams) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.xread(count, 0, streams);
        }
    }
}

